package com.tenglong.teacher.ui.homepage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.listener.OnItemSelectedListener;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.requestInfo.CreateRequestInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.RelateHeaderData;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.dialog.CreateClassDialogFragment;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.dialog.WheelDialogFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CreateClassActivity extends BaseActivity implements View.OnClickListener {
    public static final String KEY_CREATE_CLASS_TYEP = "key_create_class_type";
    public static final String KEY_RETURN_CLASS_TYPE = "key_return_class_type";
    public static final int ONE_TO_ONE = 1;
    public static final int CREATE_CLASS = 0;
    private List<RelateHeaderData.ScourseName> scourseNames;
    private ArrayList<RelateHeaderData.ScourseName> gradeNames;
    private int type;
    private TextView startClassTime;
    private TextView cource;
    private TextView grade;
    private TextView startTime, stopTime;
    private EditText teacher;
    private EditText classDuration;


    private Date startClassTimeParam;
    private String gradeParam;
    private String scourseId;
    private WheelDialogFragment selectGladeDialog;
    private WheelDialogFragment selectScourseDialog;
    private boolean isCreateClass = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_class);
        type = getIntent().getIntExtra(KEY_CREATE_CLASS_TYEP, 0);
        initView();
        setListeners();
        requestHeaderData();
    }

    private void setListeners() {
        findViewById(R.id.rl_startClassTime).setOnClickListener(this);
        findViewById(R.id.rl_grade).setOnClickListener(this);
        findViewById(R.id.rl_cource).setOnClickListener(this);
        findViewById(R.id.tvCreate).setOnClickListener(this);
        startTime.setOnClickListener(this);
        stopTime.setOnClickListener(this);
    }

    private void initView() {
        setTitle(type == CREATE_CLASS ? "创建班课" : "创建一对一");
        startClassTime = findViewById(R.id.startClassTime);
        cource = findViewById(R.id.cource);
        grade = findViewById(R.id.grade);
        startTime = findViewById(R.id.startTime);
        stopTime = findViewById(R.id.stopTime);
        classDuration = findViewById(R.id.classDuration);
        teacher = findViewById(R.id.teacher);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_startClassTime:
                selectDate(new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        startClassTime.setText(formatter.format(date));
                        startClassTime.setTextColor(Color.parseColor("#333333"));
                        startClassTimeParam = date;
                    }
                }, v);
                break;
            case R.id.rl_grade:
                selectGlade(v);
                break;
            case R.id.rl_cource:
                selectScourse(v);
                break;
            case R.id.startTime:
                setStartAndStopTime(startTime);
                break;
            case R.id.stopTime:
                setStartAndStopTime(stopTime);
                break;
            case R.id.tvCreate:
                if (TextUtils.isEmpty(gradeParam)) {
                    ToastUtils.showCenterToast("请选择班课的年级");
                    return;
                }
                if (TextUtils.isEmpty(scourseId)) {
                    ToastUtils.showCenterToast("请选择班课的科目");
                    return;
                }
                if (TextUtils.isEmpty(startClassTime.getText().toString().trim())) {
                    ToastUtils.showCenterToast("请输入班课开始时间");
                    return;
                }
                if (TextUtils.isEmpty(startTime.getText().toString().trim())) {
                    ToastUtils.showCenterToast("请输入上课时间");
                    return;
                }
                if (TextUtils.isEmpty(stopTime.getText().toString().trim())) {
                    ToastUtils.showCenterToast("请输入下课时间");
                    return;
                }
                createClass();
                break;
        }
    }

    private void setStartAndStopTime(final TextView startTime) {
        selectTime(new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
                startTime.setText(formatter.format(date));
                startTime.setTextColor(Color.parseColor("#333333"));
            }
        }, startTime);
    }

    private void createClass() {
        showProgressDialog("班级创建中...");
        CreateRequestInfo info = new CreateRequestInfo();
        info.course = scourseId;
        info.grade = gradeParam;
        info.schoolTimeEnd = stopTime.getText().toString().trim();
        info.schoolTimeStart = startTime.getText().toString().trim();
        info.teachercr = teacher.getText().toString().trim();
        info.serviceBegan = startClassTimeParam == null ? 0 : startClassTimeParam.getTime();
        info.classhour = classDuration.getText().toString().trim();
        CreateRequestEntity.getWebService().addClass(info, type == CREATE_CLASS ? 0 : 1).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    CreateClassActivity.this.isCreateClass = true;
                    DataState.getInstance().setCorrelationAnswerIsClassNumChange(true);
                    Intent data = new Intent();
                    data.putExtra(KEY_RETURN_CLASS_TYPE,type);
                    setResult(RESULT_OK,data);
                    CreateClassDialogFragment.getInstance(response.body().data).show(getSupportFragmentManager(), "createClassDialogFragment");
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }


    private void requestHeaderData() {
        CreateRequestEntity.getWebService().getAllGradeAndAllCourse().enqueue(new Callback<BaseResult<RelateHeaderData>>() {
            @Override
            public void onResponse(Call<BaseResult<RelateHeaderData>> call, Response<BaseResult<RelateHeaderData>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (scourseNames != null) {
                        scourseNames.clear();
                    } else {
                        scourseNames = new ArrayList<>();
                    }
                    if (gradeNames != null) {
                        gradeNames.clear();
                    } else {
                        gradeNames = new ArrayList<>();
                    }
                    scourseNames.addAll(response.body().data.scourseName);
                    gradeNames.addAll(response.body().data.gredesName);
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<RelateHeaderData>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }

    private void selectGlade(View view) {
        hidekeyboard(view);
        if (gradeNames == null || gradeNames.size() == 0) {
            requestHeaderData();
            return;
        }
        if (selectGladeDialog == null) {
            ArrayList<String> list = new ArrayList<>();
            for (RelateHeaderData.ScourseName scourseName : gradeNames) {
                list.add(scourseName.label);
            }
            selectGladeDialog = WheelDialogFragment.getInstance(list);
            selectGladeDialog.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(int index) {
                    RelateHeaderData.ScourseName info = gradeNames.get(index);
                    grade.setTextColor(Color.parseColor("#333333"));
                    grade.setText(info.label);
                    gradeParam = info.value;
                }
            });
        }
        selectGladeDialog.show(getSupportFragmentManager(), "selectGlade");
    }

    private void selectScourse(View view) {
        hidekeyboard(view);
        if (scourseNames == null || scourseNames.size() == 0) {
            requestHeaderData();
            return;
        }
        if (selectScourseDialog == null) {
            ArrayList<String> list = new ArrayList<>();
            for (RelateHeaderData.ScourseName scourseName : scourseNames) {
                list.add(scourseName.name);
            }
            selectScourseDialog = WheelDialogFragment.getInstance(list);
            selectScourseDialog.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(int index) {
                    RelateHeaderData.ScourseName info = scourseNames.get(index);
                    cource.setTextColor(Color.parseColor("#333333"));
                    cource.setText(info.name);
                    scourseId = info.id;
                }
            });
        }
        selectScourseDialog.show(getSupportFragmentManager(), "selectGlade");
    }

    private void selectTime(OnTimeSelectListener listener, View view) {
        hidekeyboard(view);
        TimePickerView pvTime = new TimePickerBuilder(this, listener)
                .setType(new boolean[]{false, false, false, true, true, false})
                .setSubmitColor(getResources().getColor(R.color.theme_green))
                .setCancelColor(getResources().getColor(R.color.theme_green))
                .build();
        pvTime.show();
    }

    private void selectDate(OnTimeSelectListener listener, View view) {
        hidekeyboard(view);
        TimePickerView pvTime = new TimePickerBuilder(this, listener)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setSubmitColor(getResources().getColor(R.color.theme_green))
                .setCancelColor(getResources().getColor(R.color.theme_green))
                .build();
        pvTime.show();
    }


    @Override
    public void onBackPressed() {
        if (isCreateClass){
            super.onBackPressed();
            return;
        }
        if (TextUtils.isEmpty(gradeParam) && TextUtils.isEmpty(scourseId) &&
                startTime.getText().toString().trim().equals("开始时间") &&
                stopTime.getText().toString().trim().equals("结束时间") &&
                TextUtils.isEmpty(startClassTime.getText().toString().trim()) &&
                TextUtils.isEmpty(teacher.getText().toString().trim()) &&
                TextUtils.isEmpty(classDuration.getText().toString().trim())) {
            super.onBackPressed();
        } else {
            ExitDialog.getExitDialog("是否放弃此次编辑？").setExitListener(new ExitDialog.ExitListener() {
                @Override
                public void onExit(boolean exitState) {
                    if (exitState) {
                        CreateClassActivity.super.onBackPressed();
                    }
                }
            }).show(getSupportFragmentManager(), "dialog");
        }
    }

    private void hidekeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
